import 'package:state_beacon/state_beacon.dart';
import '../models/activity_model.dart';
import 'user_state.dart';

/// 活动状态管理
class ActivityState {
  // 静态状态变量
  static List<ActivityModel> _activityList = [];
  static List<ActivityBulletModel> _bulletList = [];
  static List<ActivityShareModel> _shareList = [];
  static Map<String, List<String>> _userBadgeMap = {}; // 用户获得的勋章映射

  // State Beacon 实例
  static final activityListBeacon = Beacon.writable<List<ActivityModel>>(
    _activityList,
  );
  static final bulletListBeacon = Beacon.writable<List<ActivityBulletModel>>(
    _bulletList,
  );
  static final shareListBeacon = Beacon.writable<List<ActivityShareModel>>(
    _shareList,
  );
  static final userBadgeMapBeacon = Beacon.writable<Map<String, List<String>>>(
    _userBadgeMap,
  );

  /// 初始化默认数据
  static void _initializeDefaultData() {
    if (_activityList.isNotEmpty) return; // 避免重复初始化

    // 初始化默认活动数据
    _activityList = [
      ActivityModel(
        activityId: 'activity_001',
        title: 'Searching for lemurs',
        description:
            'Madagascar is the world\'s only remaining wild habitat for lemurs, with over 100 unique species (from nocturnal small finger monkeys to elegant crowned lemurs) that can be encountered every day.',
        imageUrl: 'assets/images/lemurs.png',
        badgeImageUrl: 'assets/images/lemurs-badge.png',
        createTime: DateTime.now().subtract(const Duration(days: 5)),
        isActive: true,
      ),
      ActivityModel(
        activityId: 'activity_002',
        title: 'Searching for the Radiant Turtle',
        description:
            'In the prickly forests and arid savannas of southern Madagascar, there is a magical creature called the Radiant Turtle, whose back armor is covered in "star patterns". As a globally endangered rare land turtle, their wild population only exists on this land. This "Tracking Star Pattern" activity not only takes you into the natural home of radiation turtles, but also allows you to become a "guardian messenger" and understand their survival wisdom through observation, injecting strength into the protection of endangered species.',
        imageUrl: 'assets/images/radiant_turtle.png',
        badgeImageUrl: 'assets/images/turtle-badge.png',
        createTime: DateTime.now().subtract(const Duration(days: 3)),
        isActive: true,
      ),
    ];

    // 初始化默认弹幕数据
    _bulletList = [
      ActivityBulletModel(
        bulletId: 'bullet_001',
        activityId: 'activity_001',
        userId: 'user_001',
        content: 'Just spotted a ring-tailed lemur family! 🐒',
        sendTime: DateTime.now().subtract(const Duration(hours: 2)),
      ),
      ActivityBulletModel(
        bulletId: 'bullet_002',
        activityId: 'activity_001',
        userId: 'user_002',
        content: 'Their social behavior is amazing!',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 30),
        ),
      ),
      ActivityBulletModel(
        bulletId: 'bullet_003',
        activityId: 'activity_001',
        userId: 'user_003',
        content: 'Madagascar wildlife never ceases to amaze me!',
        sendTime: DateTime.now().subtract(const Duration(hours: 1)),
      ),
      ActivityBulletModel(
        bulletId: 'bullet_004',
        activityId: 'activity_002',
        userId: 'user_004',
        content: 'Found a beautiful radiated tortoise today! 🐢',
        sendTime: DateTime.now().subtract(const Duration(hours: 3)),
      ),
      ActivityBulletModel(
        bulletId: 'bullet_005',
        activityId: 'activity_002',
        userId: 'user_005',
        content: 'Their star patterns are incredible!',
        sendTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
      ),
      ActivityBulletModel(
        bulletId: 'bullet_006',
        activityId: 'activity_002',
        userId: 'user_006',
        content: 'Conservation efforts are so important!',
        sendTime: DateTime.now().subtract(const Duration(hours: 2)),
      ),
    ];

    // 初始化默认用户分享数据
    _shareList = [
      ActivityShareModel(
        shareId: 'share_001',
        activityId: 'activity_001',
        userId: 'user_001',
        imageUrl: 'assets/images/lemurs-share1.png',
        shareTime: DateTime.now().subtract(const Duration(hours: 2)),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_002',
        activityId: 'activity_001',
        userId: 'user_002',
        imageUrl: 'assets/images/lemurs-share2.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 1, minutes: 30),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_003',
        activityId: 'activity_001',
        userId: 'user_003',
        imageUrl: 'assets/images/lemurs-share3.png',
        shareTime: DateTime.now().subtract(const Duration(hours: 3)),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_004',
        activityId: 'activity_001',
        userId: 'user_004',
        imageUrl: 'assets/images/lemurs-share4.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_005',
        activityId: 'activity_001',
        userId: 'user_005',
        imageUrl: 'assets/images/lemurs-share5.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_006',
        activityId: 'activity_001',
        userId: 'user_006',
        imageUrl: 'assets/images/lemurs-share6.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_007',
        activityId: 'activity_001',
        userId: 'user_007',
        imageUrl: 'assets/images/lemurs-share7.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_008',
        activityId: 'activity_001',
        userId: 'user_008',
        imageUrl: 'assets/images/lemurs-share8.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_009',
        activityId: 'activity_002',
        userId: 'user_008',
        imageUrl: 'assets/images/turtle-share1.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_010',
        activityId: 'activity_002',
        userId: 'user_009',
        imageUrl: 'assets/images/turtle-share2.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_011',
        activityId: 'activity_002',
        userId: 'user_009',
        imageUrl: 'assets/images/turtle-share3.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_012',
        activityId: 'activity_002',
        userId: 'user_010',
        imageUrl: 'assets/images/turtle-share4.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_013',
        activityId: 'activity_002',
        userId: 'user_001',
        imageUrl: 'assets/images/turtle-share5.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
      ActivityShareModel(
        shareId: 'share_014',
        activityId: 'activity_002',
        userId: 'user_002',
        imageUrl: 'assets/images/turtle-share6.png',
        shareTime: DateTime.now().subtract(
          const Duration(hours: 2, minutes: 45),
        ),
        hasReceivedBadge: true,
      ),
    ];

    // 初始化用户勋章映射
    _userBadgeMap = {
      'user_001': ['activity_001', 'activity_002'], // 用户001获得了活动001和002的勋章
      'user_002': ['activity_001', 'activity_002'], // 用户002获得了活动001和002的勋章
      'user_003': ['activity_001'], // 用户003获得了活动001的勋章
      'user_004': ['activity_001'], // 用户004获得了活动001的勋章
      'user_005': ['activity_001'], // 用户005获得了活动001的勋章
      'user_006': ['activity_001'], // 用户006获得了活动001的勋章
      'user_007': ['activity_001'], // 用户007获得了活动001的勋章
      'user_008': ['activity_001', 'activity_002'], // 用户008获得了活动001和002的勋章
      'user_009': ['activity_002'], // 用户009获得了活动002的勋章
      'user_010': ['activity_002'], // 用户010获得了活动002的勋章
    };

    // 更新 Beacon 状态
    activityListBeacon.value = List.from(_activityList);
    bulletListBeacon.value = List.from(_bulletList);
    shareListBeacon.value = List.from(_shareList);
    userBadgeMapBeacon.value = Map.from(_userBadgeMap);
  }

  /// 初始化状态
  static void initialize() {
    _initializeDefaultData();
  }

  /// 获取所有活动
  static List<ActivityModel> getAllActivities() {
    _initializeDefaultData();
    return _activityList;
  }

  /// 根据ID获取活动详情
  static ActivityModel? getActivityById(String activityId) {
    _initializeDefaultData();
    try {
      return _activityList.firstWhere(
        (activity) => activity.activityId == activityId,
      );
    } catch (e) {
      return null;
    }
  }

  /// 获取活动的弹幕列表
  static List<ActivityBulletModel> getActivityBullets(String activityId) {
    _initializeDefaultData();
    return _bulletList
        .where((bullet) => bullet.activityId == activityId)
        .toList();
  }

  /// 发送弹幕
  static void sendBullet({
    required String activityId,
    required String userId,
    required String content,
  }) {
    _initializeDefaultData();
    final newBullet = ActivityBulletModel(
      bulletId: 'bullet_${DateTime.now().millisecondsSinceEpoch}',
      activityId: activityId,
      userId: userId,
      content: content,
      sendTime: DateTime.now(),
    );
    _bulletList.add(newBullet);
    bulletListBeacon.value = List.from(_bulletList);
  }

  /// 获取活动的用户分享列表
  static List<ActivityShareModel> getActivityShares(String activityId) {
    _initializeDefaultData();
    return _shareList.where((share) => share.activityId == activityId).toList();
  }

  /// 用户分享图片到活动
  static void shareToActivity({
    required String activityId,
    required String userId,
    required String imageUrl,
  }) {
    _initializeDefaultData();
    final newShare = ActivityShareModel(
      shareId: 'share_${DateTime.now().millisecondsSinceEpoch}',
      activityId: activityId,
      userId: userId,
      imageUrl: imageUrl,
      shareTime: DateTime.now(),
      hasReceivedBadge: true, // 分享后自动获得勋章
    );
    _shareList.add(newShare);
    shareListBeacon.value = List.from(_shareList);

    // 给用户添加勋章
    _addUserBadge(userId, activityId);
  }

  /// 删除活动分享图片
  static bool removeActivityShare(String activityId, String shareId) {
    _initializeDefaultData();
    final shareIndex = _shareList.indexWhere(
      (share) => share.activityId == activityId && share.shareId == shareId,
    );

    if (shareIndex != -1) {
      _shareList.removeAt(shareIndex);
      shareListBeacon.value = List.from(_shareList);
      return true;
    }
    return false;
  }

  /// 给用户添加勋章
  static void _addUserBadge(String userId, String activityId) {
    if (!_userBadgeMap.containsKey(userId)) {
      _userBadgeMap[userId] = [];
    }

    final userBadges = List<String>.from(_userBadgeMap[userId]!);
    if (!userBadges.contains(activityId)) {
      userBadges.add(activityId);
      _userBadgeMap[userId] = userBadges;
      userBadgeMapBeacon.value = Map.from(_userBadgeMap);
    }
  }

  /// 检查用户是否已获得某个活动的勋章
  static bool hasUserReceivedBadge(String userId, String activityId) {
    _initializeDefaultData();
    final userBadges = _userBadgeMap[userId];
    return userBadges?.contains(activityId) ?? false;
  }

  /// 获取用户的所有勋章
  static List<String> getUserBadges(String userId) {
    _initializeDefaultData();
    return _userBadgeMap[userId] ?? [];
  }

  /// 获取用户在某个活动下的分享
  static List<ActivityShareModel> getUserSharesInActivity(
    String userId,
    String activityId,
  ) {
    _initializeDefaultData();
    return _shareList
        .where(
          (share) => share.userId == userId && share.activityId == activityId,
        )
        .toList();
  }

  /// 获取用户在某个活动下发送的弹幕
  static List<ActivityBulletModel> getUserBulletsInActivity(
    String userId,
    String activityId,
  ) {
    _initializeDefaultData();
    return _bulletList
        .where(
          (bullet) =>
              bullet.userId == userId && bullet.activityId == activityId,
        )
        .toList();
  }

  /// 根据用户ID获取用户信息（用于显示用户名和头像）
  static Map<String, String>? getUserInfo(String userId) {
    final user = UserState.queryUserById(userId);
    if (user != null) {
      return {'userName': user.userName, 'userAvatar': user.avatar};
    }
    return null;
  }

  /// 创建新活动（管理员功能）
  static void createActivity({
    required String title,
    required String description,
    required String imageUrl,
    required String badgeImageUrl,
  }) {
    _initializeDefaultData();
    final newActivity = ActivityModel(
      activityId: 'activity_${DateTime.now().millisecondsSinceEpoch}',
      title: title,
      description: description,
      imageUrl: imageUrl,
      badgeImageUrl: badgeImageUrl,
      createTime: DateTime.now(),
      isActive: true,
    );
    _activityList.add(newActivity);
    activityListBeacon.value = List.from(_activityList);
  }

  /// 删除活动（管理员功能）
  static bool removeActivity(String activityId) {
    _initializeDefaultData();
    final activityIndex = _activityList.indexWhere(
      (activity) => activity.activityId == activityId,
    );
    if (activityIndex == -1) return false;

    _activityList.removeAt(activityIndex);
    activityListBeacon.value = List.from(_activityList);

    // 同时删除相关的弹幕和分享数据
    _bulletList.removeWhere((bullet) => bullet.activityId == activityId);
    _shareList.removeWhere((share) => share.activityId == activityId);
    bulletListBeacon.value = List.from(_bulletList);
    shareListBeacon.value = List.from(_shareList);

    return true;
  }

  /// 切换活动状态（激活/停用）
  static bool toggleActivityStatus(String activityId) {
    _initializeDefaultData();
    final activityIndex = _activityList.indexWhere(
      (activity) => activity.activityId == activityId,
    );
    if (activityIndex == -1) return false;

    final activity = _activityList[activityIndex];
    _activityList[activityIndex] = activity.copyWith(
      isActive: !activity.isActive,
    );
    activityListBeacon.value = List.from(_activityList);
    return true;
  }

  // Getters for reactive state
  static ReadableBeacon<List<ActivityModel>> get activityList =>
      activityListBeacon;
  static ReadableBeacon<List<ActivityBulletModel>> get bulletList =>
      bulletListBeacon;
  static ReadableBeacon<List<ActivityShareModel>> get shareList =>
      shareListBeacon;
  static ReadableBeacon<Map<String, List<String>>> get userBadgeMap =>
      userBadgeMapBeacon;
}
